package cn.shuangze.assetsms.view;

import cn.shuangze.assetsms.component.CalendarPanel;
import cn.shuangze.assetsms.component.MyJTable;
import cn.shuangze.assetsms.dao.AssetsInfoDao;
import cn.shuangze.assetsms.dao.AssetsTrjnDao;
import cn.shuangze.assetsms.dao.PersonInfoDao;
import cn.shuangze.assetsms.dao.impl.AssetsInfoDaoJDBCImpl;
import cn.shuangze.assetsms.dao.impl.AssetsTrjnDaoJDBCImpl;
import cn.shuangze.assetsms.dao.impl.PersonInfoDaoJDBCImpl;
import cn.shuangze.assetsms.dao.test.OptionType;
import cn.shuangze.assetsms.entity.AssetsInfo;
import cn.shuangze.assetsms.entity.AssetsTrjn;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class AssetsTrjnManagement extends JDialog implements ActionListener, ListSelectionListener {

    //定义DAO
    private AssetsInfoDao assetsInfoDao;
    private PersonInfoDao personInfoDao;
    private AssetsTrjnDao assetsTrjnDao;
    private String[][] comboValue;
    private OptionType flag;
    private Thread showThread;

    //定义所用的面板
    private JPanel northPanel = new JPanel();
    private JPanel centerPanel = new JPanel();

    //框架的大小
    private Dimension viewSize = new Dimension(600, 300);
    private Font font = new Font("Dialog", 0, 12);

    //定义图形界面元素
    private JLabel[] jLabel = new JLabel[6];
    private JTextField[] jTextField = new JTextField[6];

    private JButton modifyBtn = new JButton(new ImageIcon("images\\save.png"));
    private JButton cancelBtn = new JButton("退出",new ImageIcon("images\\down.png"));
    private JComboBox<String> jComboBox = new JComboBox<>();

    //定义表格
    private JTable jTable;
    private DefaultTableModel tableModel;

    //定义日期选择日历
    private CalendarPanel calendarPanel = CalendarPanel.getInstance("yyyy-MM-dd");


    public AssetsTrjnManagement(OptionType flag) {

        this.flag = flag;

        assetsInfoDao = new AssetsInfoDaoJDBCImpl();
        personInfoDao = new PersonInfoDaoJDBCImpl();
        assetsTrjnDao = new AssetsTrjnDaoJDBCImpl();

        showThread = new Thread(() -> {
            try {
                showComboData();
                showTableData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "窗口初始化错误，错误原因：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        //界面初始化
        init();

    }

    private void init() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        this.setModal(true);
        this.setSize(viewSize);
        this.setResizable(false);

        //设置运行时窗口的位置
        this.setLocationRelativeTo(null);

        //北部面板的布局
        tableModel = new DefaultTableModel();  // 创建默认表格模式
        jTable = new MyJTable(tableModel);  // 创建表格 禁用编辑功能
        ListSelectionModel listSelectionModel = jTable.getSelectionModel();
        listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  // 设置表格选择模式为单一选择
        JScrollPane jScrollPane1 = new JScrollPane(jTable);  // 创建一个滚动面板，包含表格
        jScrollPane1.setPreferredSize(viewSize);  //设置滚动面板大小
        DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
        cr.setHorizontalAlignment(JLabel.CENTER);  //表格内容居中
        jTable.setDefaultRenderer(Object.class, cr);
        //jTable.getTableHeader().setReorderingAllowed(false);  //禁止表头列拖动

        northPanel.add(jScrollPane1);


        //中部面板的布局
        JPanel line1 = new JPanel();
        JPanel line2 = new JPanel();
        for (int i = 0; i < jLabel.length; i++) {
            jLabel[i] = new JLabel();
            jLabel[i].setFont(font);
            jTextField[i] = new JTextField();
            jTextField[i].setColumns(12);
            if (i == 3) {
                //日期输入框处理
                calendarPanel.register(jTextField[i]);
                jTextField[i].setEditable(false);
                jTextField[i].setBackground(new Color(0xFFFFFF));
                jTextField[i].setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }

            if (i < jLabel.length / 2) {

                line1.add(jLabel[i]);

                if (i == 2) {

                    jComboBox.setPreferredSize(new Dimension(136, 20));
                    jComboBox.setFont(font);
                    jComboBox.addItem("ssd");
                    line1.add(jComboBox);

                } else {
                    line1.add(jTextField[i]);
                }

            } else {

                line2.add(jLabel[i]);
                line2.add(jTextField[i]);
            }
        }
        jTextField[0].setEditable(false);
        jTextField[1].setEditable(false);
        jLabel[0].setText("资产编号");
        jLabel[1].setText("操作类型");
        jLabel[2].setText("操作人员");
        jLabel[3].setText("操作时间");
        jLabel[4].setText("用途说明");
        jLabel[5].setText("备注信息");

        //启动显示
        showThread.start();

        centerPanel.setLayout(new GridLayout(2, 1));
        centerPanel.add(line1);
        centerPanel.add(line2);


        //南部面板的布局
        modifyBtn.setEnabled(false);
        modifyBtn.setFont(font);
        cancelBtn.setFont(font);
        JPanel line3 = new JPanel();
        line3.add(modifyBtn);
        line3.add(cancelBtn);
        if (flag == OptionType.USING) {
            this.setTitle("资产领用管理");
            modifyBtn.setText("领用");
            jTextField[1].setText("领用");
        } else if (flag == OptionType.BACK) {
            this.setTitle("资产归还管理");
            modifyBtn.setText("归还");
            jTextField[1].setText("归还");
        } else if (flag == OptionType.INVALID) {
            this.setTitle("资产报废管理");
            modifyBtn.setText("报废");
            jTextField[1].setText("报废");
        }

        contentPane.add(centerPanel, BorderLayout.CENTER);
        contentPane.add(line3, BorderLayout.SOUTH);
        contentPane.add(northPanel, BorderLayout.NORTH);


        //添加事件
        modifyBtn.addActionListener(this);
        cancelBtn.addActionListener(this);
        listSelectionModel.addListSelectionListener(this);
        jScrollPane1.addMouseListener(new TableMouseEvent());

    }


    private void showTableData() throws Exception {

        String[][] colValue = null;
        if (flag == OptionType.USING) {
            colValue = assetsInfoDao.findAvailable();
        } else if (flag == OptionType.BACK) {
            colValue = assetsInfoDao.findUsing();
        } else if (flag == OptionType.INVALID) {
            colValue = assetsInfoDao.findUsable();
        }

        String[] colName = {"资产编号", "资产名称", "所属类型", "型号", "价格", "购买日期", "状态", "备注"};
        tableModel.setDataVector(colValue, colName);
        jTable.revalidate();  //刷新表格

    }


    private void showComboData() throws Exception {
        comboValue = personInfoDao.findAll();

        if (comboValue == null) {
            System.out.println("没有人员信息，请添加人员");

            JOptionPane.showMessageDialog(this, "没有人员信息，请先添加人员!",
                    "操作失败", JOptionPane.ERROR_MESSAGE);

            return;
        }

        jComboBox.removeAllItems();

        for (String[] strings : comboValue) {
            jComboBox.addItem(strings[1] + "-" + strings[3] + "-" + strings[4]);
        }

    }

    private void setDefaultStatus() {

        jTextField[0].setText(null);
        modifyBtn.setEnabled(false);
        jTable.getSelectionModel().clearSelection(); //取消表格选中

    }


    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();
        if (obj == cancelBtn) {
            this.dispose();

        } else if (obj == modifyBtn) {

            try {

                String assetsStatus;
                if (flag == OptionType.USING) assetsStatus = "领用";
                else if (flag == OptionType.BACK) assetsStatus = "可用";
                else if (flag == OptionType.INVALID) assetsStatus = "报废";
                else return;

                String fromAcc = jTextField[1].getText();
                int assetsId = Integer.parseInt(jTextField[0].getText());
                java.sql.Date regDate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(jTextField[3].getText()).getTime());
                int personID = Integer.parseInt(comboValue[jComboBox.getSelectedIndex()][0]);
                String purpose = jTextField[4].getText();
                String other = jTextField[5].getText();

                if (purpose.equals("")) {

                    JOptionPane.showMessageDialog(this, "用途说明不能为空！",
                            "警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                assetsInfoDao.modifyStatus(assetsId, assetsStatus);

                assetsTrjnDao.add(new AssetsTrjn(fromAcc, assetsId, regDate, personID, purpose, other));

                JOptionPane.showMessageDialog(this, "操作成功！",
                        "操作成功", JOptionPane.INFORMATION_MESSAGE);

                showTableData();


            } catch (NumberFormatException e1) {
                JOptionPane.showMessageDialog(this, "不是有效编号",
                        "警告", JOptionPane.WARNING_MESSAGE);

            } catch (Exception e2) {
                JOptionPane.showMessageDialog(this, "操作失败，错误原因：" + e2.getMessage(),
                        "操作失败", JOptionPane.ERROR_MESSAGE);
            }
        }
    }


    @Override
    public void valueChanged(ListSelectionEvent e) {

        int selectedRow = jTable.getSelectedRow();

        if (selectedRow != -1) {
            jTextField[0].setText((String) tableModel.getValueAt(selectedRow, 0));  //编号不可改
            modifyBtn.setEnabled(true);
        } else {
            setDefaultStatus();
        }

    }


    private class TableMouseEvent implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            setDefaultStatus();  //点击滚动面板空白处恢复默认状态
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
}
